package com.jty.module_login.ui.fragment

import android.graphics.Color
import android.text.InputType
import android.text.TextUtils
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import com.alibaba.android.arouter.facade.annotation.Route
import com.czl.lib_base.config.AppConstants
import com.gyf.immersionbar.ImmersionBar
import com.jty.lib_base.base.AppManager
import com.jty.lib_base.base.BaseFragment
import com.jty.lib_base.event.LiveBusCenter
import com.jty.lib_base.utils.DayModeUtil
import com.jty.lib_base.utils.SpHelper
import com.jty.lib_base.widget.EditTextMonitor
import com.jty.module_login.BR
import com.jty.module_login.R
import com.jty.module_login.databinding.LoginFragmentLoginBinding
import com.jty.module_login.viewmodel.LoginViewModel
import com.orhanobut.logger.Logger
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.subjects.PublishSubject


/**
 * author: zhouyh
 * created on: 2022/3/1 10:16 上午
 * description: 登录界面
 */
@Route(path = AppConstants.Router.Login.F_LOGIN)
class LoginFragment : BaseFragment<LoginFragmentLoginBinding, LoginViewModel>() {
    override fun initContentView(): Int {
        return R.layout.login_fragment_login
    }

    override fun initVariableId(): Int {
        return BR.viewModel
    }

    override fun useBaseLayout(): Boolean {
        return false
    }

    override fun onSupportVisible() {
        ImmersionBar.with(this).fitsSystemWindows(true)
            .statusBarDarkFont(!DayModeUtil.isNightMode(requireContext())).init()
    }

    override fun initData() {
        initBtnState()
    }

    private fun initBtnState() {
        Logger.i("account=${viewModel.model.getLoginName()},pass=${viewModel.model.getLoginPassword()}")
        if (!viewModel.savePwdState.get()) {
            SpHelper.encode(AppConstants.SpKey.LOGIN_NAME, "")
            SpHelper.encode(AppConstants.SpKey.LOGIN_PWD, "")
        }
        if (!TextUtils.isEmpty(viewModel.model.getLoginName()) &&
            !TextUtils.isEmpty(viewModel.model.getLoginPassword())
        ) {
            binding.cbState.isChecked = true
            binding.btnLogin.isEnabled = true
            binding.etAccount.setText(viewModel.model.getLoginName())
            binding.etPwd.setText(viewModel.model.getLoginPassword())
            binding.btnLogin.setBackgroundResource(R.drawable.shape_round_white)
        }

        val accountSubject = PublishSubject.create<String>()
        val pwdSubject = PublishSubject.create<String>()
        binding.etAccount.addTextChangedListener(EditTextMonitor(accountSubject))
        binding.etPwd.addTextChangedListener(EditTextMonitor(pwdSubject))



        viewModel.addSubscribe(Observable.combineLatest(
            accountSubject,
            pwdSubject
        ) { account: String, pwd: String ->
            account.isNotBlank() && pwd.isNotBlank()
        }.observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                binding.btnLogin.setTextColor(Color.parseColor("#ffffff"))
                binding.btnLogin.isEnabled = it
                binding.btnLogin.setBackgroundResource(if (it) R.drawable.shape_round_white else R.drawable.green_btn_corner_10dp)

            }
        )
    }

    override fun initViewObservable() {
        LiveBusCenter.observeRegisterSuccessEvent(this) {
            viewModel.account.set(it.account)
            viewModel.password.set(it.pwd)
        }


        viewModel.uc.passwordVisibleEvent.observe(this) {
            binding.ivEye.setImageResource(if (it) R.drawable.ic_eye else R.drawable.ic_eye_hide)
            if (it) {
                binding.etPwd.transformationMethod = HideReturnsTransformationMethod.getInstance()
            } else {
                binding.etPwd.transformationMethod = PasswordTransformationMethod.getInstance()
            }
        }

        viewModel.uc.keepAccountEvent.observe(this) {
            viewModel.model.savePwdFlag(it)
        }

    }

    override fun onBackPressedSupport(): Boolean {
        LiveBusCenter.postLogoutEvent(3)
        AppManager.instance.appExit()
        return true
    }
}